package cn.zwk.product.service.impl;

import cn.zwk.common.utils.Tree;
import cn.zwk.common.utils.TreeUtils;
import cn.zwk.product.entity.CategoryBrandRelationEntity;
import cn.zwk.product.service.CategoryBrandRelationService;
import cn.zwk.product.vo.Catelog2Vo;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.zwk.common.utils.PageUtils;
import cn.zwk.common.utils.Query;

import cn.zwk.product.dao.CategoryDao;
import cn.zwk.product.entity.CategoryEntity;
import cn.zwk.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Cacheable(value = {"category#30"}, key = "#root.methodName", sync = true)   //设置过期时间为30秒（这个只有使用redis时有效）
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> result = TreeUtils.buildSortTree(list);
        return result;
    }

    @Override
    public List<CategoryEntity> findCatelogPath(Long catId) {
        CategoryEntity root = new CategoryEntity(0L, -1L);
        List<CategoryEntity> entities = this.list();
        LinkedList<CategoryEntity> result = (LinkedList<CategoryEntity>) TreeUtils.parentPathNoRoot(entities, root, catId);
        return result;
    }

    @Override
    @Transactional
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        LambdaUpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(CategoryBrandRelationEntity::getCatelogName, category.getName())
                .eq(CategoryBrandRelationEntity::getCatelogId, category.getCatId());
        categoryBrandRelationService.update(updateWrapper);
    }

    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(
                new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> categoryEntities = TreeUtils.buildTree(list);
        Map<String, List<Catelog2Vo>> map = new LinkedHashMap<>();
        Queue<CategoryEntity> queue = new ArrayDeque<>(categoryEntities.size());

        for (CategoryEntity entity : categoryEntities) {
            map.put(entity.getCatId().toString(), new ArrayList<>());
            List<CategoryEntity> children = entity.getChildren();
            queue.addAll(children);
        }
        for (int size = queue.size(); size > 0; size--) {
            CategoryEntity curr = queue.poll();
            List<Catelog2Vo> catelog2Vos = map.get(curr.getParentCid().toString());

            //构建二级节点
            Catelog2Vo catelog2Vo = new Catelog2Vo();
            catelog2Vo.setCatalog1Id(curr.getParentCid().toString());
            catelog2Vo.setId(curr.getCatId().toString());
            catelog2Vo.setName(curr.getName());
            catelog2Vos.add(catelog2Vo);

            //构建三级节点
            if (curr.getChildren()!=null&&curr.getChildren().size()>0) {
                List<Catelog2Vo.Category3Vo> catalog3List = curr.getChildren().stream().map(categoryEntity -> {
                    Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo();
                    category3Vo.setCatalog2Id(categoryEntity.getParentCid().toString());
                    category3Vo.setId(categoryEntity.getCatId().toString());
                    category3Vo.setName(categoryEntity.getName());
                    return category3Vo;
                }).collect(Collectors.toList());

                catelog2Vo.setCatalog3List(catalog3List);
            }

        }

        return map;
    }
}
